from cancellable_timer import CancellableTimer
from random import randint, uniform
from time import sleep

i = 0

def timeout():
    global i
    print("It takes a long time to respond, timeout!. Modify i to 1") 
    i = 1

def emergency_cancel(job):
    global i
    if job.cancel():
        print("Successfully cancelled. Modify i to -1")
        i = -1

job = CancellableTimer(interval=2, function=timeout)
job.start()

rd = uniform(0, 4)
print("random is {}".format(rd))
if rd < 2:
    sleep(rd)
    emergency_cancel(job)
    sleep(5 - rd)
else:
    job.join()

print(i)